package com.hry.store.service.impl;

import com.hry.store.common.Const;
import com.hry.store.redis.RedisComponent;
import com.hry.store.service.VerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Random;

@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {
    @Autowired
    RedisComponent redisComponent;

    /**
     * 生成验证码
     * @return
     */
    public BufferedImage createVerifyCode(HttpServletResponse response) {
        int width = 80;
        int height = 32;
        //create the image
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // set the background color
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        // draw the border
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        // create a random instance to generate the codes
        Random rdm = new Random();
        // make some confusion
        for (int i = 0; i < 50; i++) {
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
        // generate a random code
        String verifyCode = generateVerifyCode(rdm);
        g.setColor(new Color(255, 103, 0));
        g.setFont(new Font("Candara", Font.BOLD, 24));
        g.drawString(verifyCode, 3, 24);
        g.dispose();
        //把验证码存到cookie中
        int rnd = calc(verifyCode);
//        redisComponent.sentinelSet("login_verify_code", String.valueOf(rnd));
        Cookie cookie = new Cookie(Const.LOGIN_VERIFY, String.valueOf(rnd));
        cookie.setPath("/");
        cookie.setMaxAge(300);
        response.addCookie(cookie);

        //输出图片
        return image;
    }

    /**
     * 检验验证码
     * @param verifyCode
     * @param request
     * @return
     */
    @Override
    public Boolean checkVerifyEmail(int verifyCode, HttpServletRequest request) throws UnsupportedEncodingException {
        String codeValue = null;
        // 遍历cookie
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(Const.LOGIN_VERIFY)) {
                codeValue = URLDecoder.decode(cookie.getValue(), "UTF-8");
            }
        }

        // 验证码校验成功
        if (verifyCode - Integer.parseInt(codeValue) == 0) {
            return true;
        }
        return false;
    }

    private static int calc(String exp) {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            return (Integer)engine.eval(exp);
        }catch(Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    private static char[] ops = new char[] {'+', '-', '*'};
    private String generateVerifyCode(Random rdm) {
        int num1 = rdm.nextInt(10);
        int num2 = rdm.nextInt(10);
        int num3 = rdm.nextInt(10);
        char op1 = ops[rdm.nextInt(3)];
        char op2 = ops[rdm.nextInt(3)];
        String exp = ""+ num1 + op1 + num2 + op2 + num3;
        return exp;
    }



}
